import { defineEventHandler, getCookie, readBody, createError } from 'h3';
import { BackupManager } from '../../utils/backup.js';
import { CloudBackupManager } from '../../utils/cloudBackup.js';

export default defineEventHandler(async (event) => {
  try {
    const userId = getCookie(event, 'userId');
    if (!userId) {
      throw createError({ statusCode: 401, statusMessage: 'Unauthorized' });
    }

    const { filename, cloudConfig } = await readBody(event);
    if (!filename) {
      throw createError({ statusCode: 400, statusMessage: 'Filename is required' });
    }

    if (!cloudConfig) {
      throw createError({ statusCode: 400, statusMessage: 'Cloud configuration is required' });
    }

    // 获取本地备份文件
    const backupManager = new BackupManager();
    const backupPath = backupManager.backupDir + '/' + filename;
    
    // 创建云备份管理器
    const cloudManager = new CloudBackupManager(cloudConfig);
    
    // 上传到云端
    const result = await cloudManager.uploadBackup(backupPath, filename);

    return {
      success: true,
      message: '备份上传到云端成功',
      cloudBackup: result
    };
  } catch (error) {
    console.error('上传备份到云端失败:', error);
    throw createError({ statusCode: 500, statusMessage: 'Failed to upload backup to cloud' });
  }
});
